﻿using System.Collections.Generic;
using System.Data;
using IceCS.GoodsSale.Models.UserModels;
using Microsoft.Data.SqlClient;

namespace IceCS.GoodsSale.DAL
{
    public class UserAccesser
    {
        //定义DBHelper类的对象，使用其数据操作方法
        DBHelper dh = new DBHelper();
        //定义PublicMethodsDAL类的对象，修改密码时使用MD5加密方法
        PublicMethodsAccesser publicMethodsDAL = new PublicMethodsAccesser();

        //查询一条用户记录的方法
        public User SelectUser(string userName)
        {
            string sqlStr = "select * from TB_User where UserName='" + userName + "'";
            DataTable dt = dh.GetDataTable(sqlStr);
            User user = new User();
            if (dt.Rows.Count != 0)
            {
                user.UserName = dt.Rows[0].ItemArray[0].ToString();
                user.UserPassword = dt.Rows[0].ItemArray[1].ToString();
                user.UserType = dt.Rows[0].ItemArray[2].ToString();
                return user;
            }
            else
            {
                return null;
            }
        }

        //修改一条用户记录的方法
        public bool UpdateUserPassword(string userName, string userPassword)
        {
            string md5UserPassword = publicMethodsDAL.GetMd5Str(userPassword);
            string sqlStr = "update TB_User set UserPassword=@UserPassword where UserName=@UserName";
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@UserPassword",md5UserPassword),
                new SqlParameter("@UserName",userName),
            };
            return dh.ExcuteCommand(sqlStr, param);
        }

        //查询多条用户记录的方法，返回一个用户名列表
        public List<User> SelectUserNames()
        {
            string sqlStr = "select UserName from TB_User";
            DataTable dt = dh.GetDataTable(sqlStr);
            List<User> list = new List<User>();
            foreach (DataRow r in dt.Rows)
            {
                User user = new User();
                user.UserName = r["UserName"].ToString();
                list.Add(user);
            }
            return list;
        }
    }
}
